<template>
    <div class="xd_bill_form_container">
        <el-form ref="jxcFinBillForm" :rules="rules" :model="formData" label-width="110px"
                 v-enterToNext>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="往来单位" prop="related_party_sid">
                        <vSelectBottom v-model="formData.related_party_sid" type="custom"
                                       @event="handleRelatedPartyEvent" :options="relatedPartyOptions"
                                       :disabled="!isEditFlag"/>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="账单日期" prop="the_date">
                        <el-date-picker v-model="formData.the_date" type="date"
                                        value-format="yyyy-MM-dd"
                                        :disabled="!isEditFlag" style="width: 100%;"/>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="账单号码" prop="code">
                        <el-input v-model="formData.code" autocomplete="off" clearable placeholder="留空则系统自动编码"
                                  :disabled="!isEditFlag"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item :label="`${type==='cash_in'?'收':'付'}款类型`" prop="bill_type">
                        <el-select v-model="formData.bill_type" clearable :disabled="!isEditFlag"
                                   style="width: 100%;">
                            <el-option v-for="(item, index) in validTypeList" :key="index"
                                       :label="item.display_text" :value="item.key3"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="资金账号" prop="fund_account_sid">
                        <vSelectBottom v-model="formData.fund_account_sid" type="custom"
                                       :options="fundAccountOptions" :tree-options="fundAccountTreeOptions"
                                       :disabled="!isEditFlag"/>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="账单金额" prop="amount">
                        <el-input v-model="formData.amount" autocomplete="off" clearable
                                  :disabled="!isEditFlag" v-double-input="{ len: 4, negative: false }"/>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="经手人" prop="dealer_name">
                        <el-input v-model="formData.dealer_name" autocomplete="off" clearable
                                  :disabled="!isEditFlag"/>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="摘要" prop="note_info">
                        <el-input type="textarea" v-model="formData.note_info" autocomplete="off" clearable
                                  :disabled="!isEditFlag" :row="3"/>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script>
import {mapState} from "vuex";
import FundAccountForm from "@common/views/base/dialog/FundAccountForm";

export default {
    name: "JxcFinBillForm",
    props: {
        type: {
            type: String,
            default: 'cash_in',
        },
        row: {
            type: Object,
            default: null,
        },
        detail: {
            type: Boolean,
            default: false,
        },
        typeList: {
            type: Array,
            default: null,
        },
    },
    data() {
        const _this = this;
        return {
            rules: _this.detail ? {} : {
                code: [
                    {required: true, message: "请输入账单号码", trigger: "blur"},
                    {max: 32, message: "最大 32 位字符，内容过长，请删减", trigger: "blur",},
                ],
                related_party_sid: [
                    {required: true, message: "请选择往来单位", trigger: "change"},
                ],
                bill_type: [
                    {
                        required: true,
                        message: `请选择${_this.type === 'cash_in' ? '收' : '付'}款类型`,
                        trigger: "change"
                    },
                ],
                the_date: [
                    {required: true, message: "请选择账单日期", trigger: "change"},
                ],
                amount: [
                    {required: true, message: "请输入账单金额", trigger: "blur"},
                ],
            },
            oldCode: '',
            formData: {},
            relatedPartyOptions: {
                url: _this.$api.API_FindBaseRelatedPartys,
                params(query) {
                    const rec_type_list = _this.type === 'cash_in' ? [1, 3] : [2, 3];
                    return $.extend({}, query, {
                        is_group: 0,
                        rec_type_list,
                    });
                },
                disabled: false,
                placeholder: '请选择往来单位',
                bottomAction: {
                    permission: 'jxc:relatedParty:save',
                    permissionUrl: '/jxcBaseRelated',
                },
                props: {
                    value: "sid",
                    label: 'display',
                },
            },
            baseFundAccountList: [],
            fundAccountOptions: {
                placeholder: '',
                url: _this.$api.API_FindBaseFundAccounts,
                props: {
                    label: 'name',
                    value: 'sid',
                },
                tree: true,
                bottomAction: {
                    permission: 'jxc:fundAccount:save',
                    permissionUrl: '/jxcFinFundAccount',
                    addComponent: FundAccountForm,
                    width: '720px',
                    title: '创建资金账号',
                },
            },
            fundAccountTreeOptions: {
                nodeKey: 'sid',
                props: {
                    label: 'name',
                    value: 'sid',
                },
            },
        };
    },
    computed: {
        ...mapState(['userInfo']),
        isEditFlag() {
            if (this.detail) {
                return false;
            }
            return this.$utils.isEmpty(this.formData.audit_state) || this.formData.audit_state === 0;
        },
        validTypeList() {
            let list = (this.typeList || []).map(item => $.extend({}, item));
            if (this.$utils.isNotEmpty(this.type)) {
                list = list.filter(item => item.key2 === this.type);
            }
            return list;
        },
    },
    watch: {
        row: {
            handler() {
                this.init();
            },
            deep: true,
            immediate: true,
        },
    },
    methods: {
        async init() {
            const _this = this;
            if (!_this.row) {
                return;
            }
            if (_this.$refs.jxcFinBillForm) {
                _this.$refs.jxcFinBillForm.clearValidate();
            }
            let sid = _this.$route.query.sid;
            if (_this.$utils.isNotEmpty(_this.row.sid)) {
                sid = _this.row.sid;
            }
            if (_this.$utils.isNotEmpty(sid)) {
                await _this.initData(_this.row.sid);
            } else {
                _this.formData = {
                    the_date: _this.$XEUtils.toDateString(new Date(), 'yyyy-MM-dd'),
                    dealer_name: _this.userInfo.group_person_name,
                };
            }
        },
        initData(sid) {
            const _this = this;
            return _this.fetchData(_this.$api.API_GetJxcFinanceFundDetailBySid, {
                sid,
            }).then(result => {
                _this.formData = result.data || {};
                _this.oldCode = resData.code;
            }).catch(() => {
            });
        },
        generateCode() {
            const _this = this;
            if (_this.$utils.isNotEmpty(_this.oldCode) && _this.oldCode === _this.formData.code) {
                return;
            }
            return _this.storeDispatch('base/getAutoOrderCode', {
                rule_code: 'jxc_finance_recv_pay_bill',
                related_party_sid: _this.formData.related_party_sid,
            }).then(data => {
                _this.formData = $.extend({}, _this.formData, {
                    code: data,
                });
                _this.oldCode = data;
                if (_this.$refs.jxcFinBillForm) {
                    _this.$refs.jxcFinBillForm.clearValidate('code');
                }
            });
        },
        handleClientEvent(event) {
            const _this = this;
            if (!_this.isEditFlag) {
                return;
            }
            if (typeof event.value !== 'undefined' && _this.$utils.isNotEmpty(event.value)) {
                _this.formData = $.extend({}, _this.formData, {
                    client_sid: event.value,
                });
                if (_this.isEditFlag) {
                    _this.generateCode();
                }
            }
        },
        handleRelatedPartyEvent(event) {
            const _this = this;
            if (!_this.isEditFlag) {
                return;
            }
            if (typeof event.value !== 'undefined' && _this.$utils.isNotEmpty(event.value)) {
                _this.formData = $.extend({}, _this.formData, {
                    related_party_sid: event.value,
                });
                if (_this.isEditFlag) {
                    _this.generateCode();
                }
            }
        },
        async confirm() {
            const _this = this;
            let valid = await _this.validateForm('jxcFinBillForm');
            if (!valid) {
                return false;
            }
            let subData = $.extend({}, _this.formData);
            subData.type = _this.type;
            return _this.fetchData(_this.$api.API_SaveJxcFinanceFundDetail, subData).then(() => {
                _this.$message.success('保存成功！');
                return true;
            }).catch(() => {
                return false;
            });
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.xd_bill_form_container {
    width: 100%;
    height: 100%;
}
</style>
